package com.ruoyi.service.jpjs.municipal.impl;

import com.ruoyi.common.constant.MsgConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.CopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.Md5Utils;
import com.ruoyi.domain.jpjs.common.machinery.Machinery;
import com.ruoyi.domain.jpjs.common.machinery.MachineryDay;
import com.ruoyi.domain.jpjs.common.machinery.MachineryImport;
import com.ruoyi.domain.jpjs.common.machinery.MachineryNewMonth;
import com.ruoyi.domain.jpjs.common.mater.Mater;
import com.ruoyi.domain.jpjs.common.mater.MaterCount;
import com.ruoyi.domain.jpjs.common.mater.MaterDay;
import com.ruoyi.domain.jpjs.common.mater.MaterImport;
import com.ruoyi.domain.jpjs.common.municipal.expend.Manage;
import com.ruoyi.domain.jpjs.common.municipal.expend.Team;
import com.ruoyi.mapper.jpjs.manage.ManageMapper;
import com.ruoyi.service.jpjs.municipal.ManageService;

import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.domain.SysDictSon;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.SysDictSonMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @explain 市政收入 业务层处理
 */
@Service
public class ImanageServiceImpl implements ManageService {

    @Resource
    private ManageMapper manageMapper;

    @Resource
    private SysDictDataMapper sysDictDataMapper;

    @Resource
    private SysDictSonMapper sysDictSonMapper;

    @Override
    public List<Mater> queryMaterForQuantity(Mater mater) {
        return manageMapper.queryMaterForQuantity(mater);
    }

    @Override
    public List<Mater> queryMaterForCount(Mater mater) {
        return manageMapper.queryMaterForCount(mater);
    }

    @Override
    public List<Manage> queryManageList(Manage manage) {
        return manageMapper.queryManageList(manage);
    }

    @Override
    public int insertManage(Manage manage) {
        return manageMapper.insertManage(manage);
    }

    @Override
    public String checkMonthUnique(Manage manage) {
        int count = manageMapper.checkMonthUnique(manage);
        if (count > 0) {
            return MsgConstants.MONTH_NOT_UNIQUE;
        }
        return MsgConstants.MONTH_UNIQUE;
    }

    @Override
    public String checkMonthUniqueEdit(Manage manage) {
        int count = manageMapper.checkMonthUniqueEdit(manage);
        if (count > 0) {
            return MsgConstants.MONTH_NOT_UNIQUE;
        }
        return MsgConstants.MONTH_UNIQUE;
    }

    @Override
    public int updateManage(Manage manage) {
        return manageMapper.updateManage(manage);
    }

    @Override
    public int deleteManageById(String manage) {
        String[] manageId = Convert.toStrArray(manage);
        return manageMapper.deleteManageById(manageId);
    }

    @Override
    public List<Team> queryTeamList(Team team) {
        return manageMapper.queryTeamList(team);
    }

    @Override
    public int insertTeam(Team team) {
        return manageMapper.insertTeam(team);
    }

    @Override
    public int updateTeam(Team team) {
        return manageMapper.updateTeam(team);
    }

    @Override
    public int deleteTeamById(String team) {
        String[] teamId = Convert.toStrArray(team);
        return manageMapper.deleteTeamById(teamId);
    }

    @Override
    public List<Mater> queryMaterList(Mater mater) {
        return manageMapper.queryMaterList(mater);
    }

    @Override
    public List<MaterDay> queryMaterDayList(MaterDay materDay) {
        return manageMapper.queryMaterDayList(materDay);
    }

    @Override
    public int insertMaterialDay(MaterDay materDay) {
        return manageMapper.insertMaterialDay(materDay);
    }

    @Override
    public int updateMaterialDay(MaterDay materDay) {
        return manageMapper.updateMaterialDay(materDay);
    }

    @Override
    public String checkPurchaseDateUnique(MaterDay materDay) {
        int count = manageMapper.checkPurchaseDateUnique(materDay);
        if (count > 0) {
            return MsgConstants.MONTH_NOT_UNIQUE;
        }
        return MsgConstants.MONTH_UNIQUE;
    }

    @Override
    public int checkPurchaseDateUniqueEdit(MaterDay materDay) {
        return manageMapper.checkPurchaseDateUniqueEdit(materDay);
    }

    @Override
    public int deleteMaterialDayById(String ids) {
        String[] id = Convert.toStrArray(ids);
        return manageMapper.deleteMaterialDayById(id);
    }

    @Override
    public int updateMater(Mater mater) {
        return manageMapper.updateMater(mater);
    }

    @Override
    public int addMater(Mater mater) {
        return manageMapper.addMater(mater);
    }

    @Override
    public List<MaterDay> queryMaterDayListBypId(MaterDay materDay) {
        return manageMapper.queryMaterDayListBypId(materDay);
    }

    @Override
    public String checkMaterUnique(Mater mater) {
        int count = manageMapper.checkMaterUnique(mater);
        if (count > 0) {
            return MsgConstants.MONTH_NOT_UNIQUE;
        }
        return MsgConstants.MONTH_UNIQUE;
    }

    @Override
    public String checkMaterUniqueEdit(Mater mater) {
        int count = manageMapper.checkMaterUniqueEdit(mater);
        if (count > 0) {
            return MsgConstants.MONTH_NOT_UNIQUE;
        }
        return MsgConstants.MONTH_UNIQUE;
    }

    @Override
    public int checkMaterUniqueAdd(Mater mater) {
        return manageMapper.checkMaterUniqueAdd(mater);
    }

    @Override
    @Transactional
    public int deleteMaterialById(String materialIds) {
        String[] materialId = Convert.toStrArray(materialIds);
        manageMapper.deleteMaterialDayBypId(materialId);
        return manageMapper.deleteMaterialById(materialId);
    }

    @Override
    public List<Mater> queryMonthList(Mater mater) {
        return manageMapper.queryMonthList(mater);
    }

    @Override
    public List<Mater> queryMaterForPrevious(Mater mater) {
        return manageMapper.queryMaterForPrevious(mater);
    }

    @Override
    public int insertMachinery(Machinery machinery) {
        return manageMapper.insertMachinery(machinery);
    }

    @Override
    public List<Machinery> queryMachinerylist(Machinery machinery) {
        return manageMapper.queryMachinerylist(machinery);
    }

    @Override
    public String checkMachineryUniqueAdd(Machinery machinery) {
        int count = manageMapper.checkMachineryUniqueAdd(machinery);
        if (count > 0) {
            return MsgConstants.MONTH_NOT_UNIQUE;
        }
        return MsgConstants.MONTH_UNIQUE;
    }

    @Override
    public String checkMachineryUniqueEdit(Machinery machinery) {
        int count = manageMapper.checkMachineryUniqueEdit(machinery);
        if (count > 0) {
            return MsgConstants.MONTH_NOT_UNIQUE;
        }
        return MsgConstants.MONTH_UNIQUE;

    }

    @Override
    public int updateMachinery(Machinery machinery) {
        return manageMapper.updateMachinery(machinery);
    }

    @Override
    public List<MachineryDay> queryMachineryDayList(MachineryDay machineryDay) {
        return manageMapper.queryMachineryDayList(machineryDay);
    }

    @Override
    public int insertMachineryDay(MachineryDay machineryDay) {
        return manageMapper.insertMachineryDay(machineryDay);
    }

    @Override
    public String checkDateUnique(MachineryDay machineryDay) {
        int count = manageMapper.checkDateUnique(machineryDay);
        if (count > 0) {
            return MsgConstants.MONTH_NOT_UNIQUE;
        }
        return MsgConstants.MONTH_UNIQUE;
    }

    @Override
    public List<MachineryDay> queryMachineryDayListBypId(MachineryDay machineryDay) {
        return manageMapper.queryMachineryDayListBypId(machineryDay);
    }

    @Override
    public String checkDateUniqueEdit(MachineryDay machineryDay) {
        int count = manageMapper.checkDateUniqueEdit(machineryDay);
        if (count > 0) {
            return MsgConstants.MONTH_NOT_UNIQUE;
        }
        return MsgConstants.MONTH_UNIQUE;
    }

    @Override
    public int updateMachineryDay(MachineryDay machineryDay) {
        return manageMapper.updateMachineryDay(machineryDay);
    }

    @Override
    public int deleteMachineryDayById(String ids) {
        String[] id = Convert.toStrArray(ids);
        return manageMapper.deleteMachineryDayById(id);
    }

    @Override
    public int updateMachineryMonthTotalPrice(Machinery machinery) {
        return manageMapper.updateMachineryMonthTotalPrice(machinery);
    }

    @Override
    public List<Machinery> queryMachineryForCount(Machinery machinery) {
        return manageMapper.queryMachineryForCount(machinery);
    }

    @Override
    public int updateMachineryTotalPrice(Machinery machinery) {
        return manageMapper.updateMachineryTotalPrice(machinery);
    }

    @Override
    @Transactional
    public int deleteMachineryById(String machineryIds) {
        String[] machineryId = Convert.toStrArray(machineryIds);
        manageMapper.deleteMachineryDayBypId(machineryId);
        return manageMapper.deleteMachineryById(machineryId);
    }

    @Override
    public List<Machinery> queryMachinerylistMonth(Machinery machinery) {
        return manageMapper.queryMachinerylistMonth(machinery);
    }

    @Override
    public List<Machinery> queryMachineryForCountMonth(Machinery machinery) {
        return manageMapper.queryMachineryForCountMonth(machinery);
    }

    @Override
    public int insertMachineryMonth(Machinery machinery) {
        return manageMapper.insertMachineryMonth(machinery);
    }

    @Override
    public String checkMachineryUniqueAddMonth(Machinery machinery) {
        int count = manageMapper.checkMachineryUniqueAddMonth(machinery);
        if (count > 0) {
            return MsgConstants.MONTH_NOT_UNIQUE;
        }
        return MsgConstants.MONTH_UNIQUE;
    }

    @Override
    public String checkMachineryUniqueEditMonth(Machinery machinery) {
        int count = manageMapper.checkMachineryUniqueEditMonth(machinery);
        if (count > 0) {
            return MsgConstants.MONTH_NOT_UNIQUE;
        }
        return MsgConstants.MONTH_UNIQUE;
    }

    @Override
    public int updateMachineryMonth(Machinery machinery) {
        return manageMapper.updateMachineryMonth(machinery);
    }

    @Override
    public int deleteMachineryByIdMonth(String machineryIds) {
        String[] machineryId = Convert.toStrArray(machineryIds);
        manageMapper.deleteMachineryDayBypIdMonth(machineryId);
        return manageMapper.deleteMachineryByIdMonth(machineryId);
    }

    @Override
    public List<MachineryDay> queryMachineryDayListMonth(MachineryDay machineryDay) {
        return manageMapper.queryMachineryDayListMonth(machineryDay);
    }

    @Override
    public int insertMachineryDayMonth(MachineryDay machineryDay) {
        return manageMapper.insertMachineryDayMonth(machineryDay);
    }

    @Override
    public String checkDateUniqueMonth(MachineryDay machineryDay) {
        int count = manageMapper.checkDateUniqueMonth(machineryDay);
        if (count > 0) {
            return MsgConstants.MONTH_NOT_UNIQUE;
        }
        return MsgConstants.MONTH_UNIQUE;
    }

    @Override
    public List<MachineryDay> queryMachineryDayListBypIdMonth(MachineryDay machineryDay) {
        return manageMapper.queryMachineryDayListBypIdMonth(machineryDay);
    }

    @Override
    public String checkDateUniqueEditMonth(MachineryDay machineryDay) {
        int count = manageMapper.checkDateUniqueEditMonth(machineryDay);
        if (count > 0) {
            return MsgConstants.MONTH_NOT_UNIQUE;
        }
        return MsgConstants.MONTH_UNIQUE;
    }

    @Override
    public int updateMachineryDayMonth(MachineryDay machineryDay) {
        return manageMapper.updateMachineryDayMonth(machineryDay);
    }

    @Override
    public int deleteMachineryDayByIdMonth(String ids) {
        String[] id = Convert.toStrArray(ids);
        return manageMapper.deleteMachineryDayByIdMonth(id);
    }

    @Override
    @Transactional
    public String importMachineryDay(List<MachineryDay> machineryDayList, String machineryId) {
        if (StringUtils.isNull(machineryDayList) || machineryDayList.size() == 0) {
            throw new BusinessException("导入机械每日数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (MachineryDay machineryDay : machineryDayList) {
            try {
                // 日期格式转化
                String dateString = machineryDay.getPurchaseDate().trim();
                String dateStr = FormatDate(dateString);
                machineryDay.setPurchaseDate(dateStr);

                machineryDay.setPId(Integer.valueOf(machineryId));
                // 验证是否存在相同日期
                int count = manageMapper.checkDateUnique(machineryDay);
                if (count > 0) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、采购日期 " + machineryDay.getPurchaseDate() + " 已存在");
                } else {
                    this.insertMachineryDay(machineryDay);
                    Machinery machinery = updateMachineryPurchase(machineryDay);
                    manageMapper.updateMachinery(machinery);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、采购日期 " + machineryDay.getPurchaseDate() + " 导入成功");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、采购日期 " + machineryDay.getPurchaseDate() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    @Override
    public String importMachineryDayMonth(List<MachineryDay> machineryDayList, String machineryId) {
        if (StringUtils.isNull(machineryDayList) || machineryDayList.size() == 0) {
            throw new BusinessException("导入机械每日数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (MachineryDay machineryDay : machineryDayList) {
            try {
                // 日期格式转化
                String dateString = machineryDay.getPurchaseDate().trim();
                String dateStr = FormatDate(dateString);
                machineryDay.setPurchaseDate(dateStr);

                machineryDay.setPId(Integer.valueOf(machineryId));
                // 验证是否存在相同日期
                int count = manageMapper.checkDateUniqueMonth(machineryDay);
                if (count > 0) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、采购日期 " + machineryDay.getPurchaseDate() + " 已存在");
                } else {
                    this.insertMachineryDayMonth(machineryDay);
                    Machinery machinery = updateMachineryPurchaseMonth(machineryDay);
                    manageMapper.updateMachineryMonth(machinery);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、采购日期 " + machineryDay.getPurchaseDate() + " 导入成功");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、采购日期 " + machineryDay.getPurchaseDate() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public Machinery updateMachineryPurchase(MachineryDay machineryDay) {
        List<MachineryDay> machineryDays = manageMapper.queryMachineryDayListBypId(machineryDay);
        double workTimeTotal = 0;
        double fuelConsumpTotal = 0;
        if (StringUtils.isNotEmpty(machineryDays)) {
            for (MachineryDay machineryObj : machineryDays) {
                double workTimeDay = Double.valueOf(machineryObj.getWorkTimeDay());
                Integer fuelDayConsump = Integer.valueOf(machineryObj.getFuelDayConsump());
                workTimeTotal = workTimeTotal + workTimeDay;
                fuelConsumpTotal = fuelConsumpTotal + fuelDayConsump;
            }
        }
        Machinery machinery = new Machinery();
        machinery.setMachineryId(machineryDay.getPId());
        machinery.setWorkTime(workTimeTotal);
        machinery.setFuelMonthConsump(fuelConsumpTotal);
        return machinery;
    }

    @Override
    public Machinery updateMachineryPurchaseMonth(MachineryDay machineryDay) {
        List<MachineryDay> machineryDays = manageMapper.queryMachineryDayListBypIdMonth(machineryDay);
        double workTimeTotal = 0;
        double fuelConsumpTotal = 0;
        if (StringUtils.isNotEmpty(machineryDays)) {
            for (MachineryDay machineryObj : machineryDays) {
                double workTimeDay = Double.valueOf(machineryObj.getWorkTimeDay());

                if (workTimeDay != 0) {
                    workTimeTotal = workTimeTotal + 1;
                }
                Integer fuelDayConsump = Integer.valueOf(machineryObj.getFuelDayConsump());
                fuelConsumpTotal = fuelConsumpTotal + fuelDayConsump;
            }
        }
        Machinery machinery = new Machinery();
        machinery.setMachineryId(machineryDay.getPId());
        machinery.setWorkTime(workTimeTotal);
        machinery.setFuelMonthConsump(fuelConsumpTotal);
        return machinery;
    }

    @Override
    public String importMaterDay(List<MaterDay> materDayList, String materId) {
        if (StringUtils.isNull(materDayList) || materDayList.size() == 0) {
            throw new BusinessException("导入材料每日数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (MaterDay materDay : materDayList) {
            try {
                String dateString = materDay.getPurchaseDate().trim();
                String dateStr = FormatDate(dateString);
                materDay.setPurchaseDate(dateStr);


                materDay.setMaterialId(Integer.valueOf(materId));
                // 验证是否存在相同日期
                int count = manageMapper.checkPurchaseDateUnique(materDay);
                if (count > 0) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、采购日期 " + materDay.getPurchaseDate() + " 已存在");
                } else {
                    this.insertMaterialDay(materDay);
                    Mater mater = updateMaterPurchase(materDay);
                    manageMapper.updateMater(mater);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、采购日期 " + materDay.getPurchaseDate() + " 导入成功");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、采购日期 " + materDay.getPurchaseDate() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    private String FormatDate(String dateString) {
        Date time = new Date(dateString);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(time).substring(0, sdf.format(time).indexOf(' '));
    }

    @Override
    public Mater updateMaterPurchase(MaterDay materDay) {
        List<MaterDay> materDays = manageMapper.queryMaterDayListBypId(materDay);
        double sum = 0;
        if (StringUtils.isNotEmpty(materDays)) {
            for (MaterDay materObj : materDays) {
                Integer purchaseQuantity = Integer.valueOf(materObj.getPurchaseQuantity());
                sum = sum + purchaseQuantity;
            }
        }
        Mater mater = new Mater();
        mater.setMaterialId(materDay.getMaterialId());
        mater.setPurchaseQuantity(sum);
        return mater;
    }

    @Override
    public int updateMaterCount(MaterCount materCount) {
        return manageMapper.updateMaterCount(materCount);
    }

    @Override
    public int queryMaterCount(MaterCount materCount) {
        return manageMapper.queryMaterCount(materCount);
    }

    @Override
    public int insertMaterCount(MaterCount materCount) {
        return manageMapper.insertMaterCount(materCount);
    }

    @Override
    public int deleteMaterCount() {
        return manageMapper.deleteMaterCount();
    }

    @Override
    public String importMachinery(List<MachineryImport> list, MachineryImport machineryImport) {
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new BusinessException("导入材料月数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (MachineryImport machinery : list) {
            try {
                // Step1 转化名称转ID
                String dateString = machinery.getActualMonth().trim();
                String dateStr = FormatDate(dateString).substring(0, 7);
                machinery.setActualMonth(dateStr);

                String entryTimeStr = machinery.getEntryTime().trim();
                machinery.setEntryTime(FormatDate(entryTimeStr));   // 进场时间

                String exitTimeStr = machinery.getExitTime().trim();
                machinery.setExitTime(FormatDate(exitTimeStr));   // 退场时间

                // 出租单位转化
                String rentalIdName = machinery.getRentalIdName();
                SysDictData sysDictData = new SysDictData();
                sysDictData.setDictLabel(rentalIdName);
                SysDictData data = sysDictDataMapper.selectDictData(sysDictData);
                if (data == null) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、出租单位:" + machinery.getRentalIdName() + " 不存在");
                } else {
                    machinery.setRentalId(Integer.valueOf(data.getDictCode().toString()));    // 供应商ID

                    // 机械编号转化
                    SysDictSon sysDictSon = new SysDictSon();
                    sysDictSon.setDictCode(Integer.valueOf(data.getDictCode().toString()));
                    sysDictSon.setLable(machinery.getMachineryNumberIdName());
                    SysDictSon son = sysDictDataMapper.selectDictSonByCodeAndLable(sysDictSon);

                    if (son != null) {
                        machinery.setMachineryNumberId(son.getId());      // 物料名称ID
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、机械编号:" + machinery.getMachineryNumberIdName() + " 不存在");
                    }
                }
                machinery.setCompanyId(machineryImport.getCompanyId());
                machinery.setProgramId(machineryImport.getProgramId());

                // Step2 唯一性校验：同一个项目下,月份、出租单位、机械编号的唯一性
                Machinery machineryObj = new Machinery();
                CopyUtils.Copy(machinery, machineryObj);
                int count = manageMapper.checkMachineryUniqueAdd(machineryObj);
                if (count > 0) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、项目下,月份、出租单位、机械编号不符合唯一性");
                }else{
                    manageMapper.insertMachinery(machineryObj);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、出租单位:" + machinery.getRentalIdName() + " 导入成功");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、供应商名称 " + machinery.getRentalIdName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String importMachineryMonth(List<MachineryNewMonth> list, MachineryNewMonth machineryNewMonth) {
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new BusinessException("导入材料月数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (MachineryNewMonth machineryNewMon : list) {
            try {
                // Step1 转化名称转ID
                String dateString = machineryNewMon.getActualMonth().trim();
                String dateStr = FormatDate(dateString).substring(0, 7);
                machineryNewMon.setActualMonth(dateStr);

                String entryTimeStr = machineryNewMon.getEntryTime().trim();
                machineryNewMon.setEntryTime(FormatDate(entryTimeStr));   // 进场时间

                String exitTimeStr = machineryNewMon.getExitTime().trim();
                machineryNewMon.setExitTime(FormatDate(exitTimeStr));   // 退场时间

                // 出租单位转化
                String rentalIdName = machineryNewMon.getRentalIdName();
                SysDictData sysDictData = new SysDictData();
                sysDictData.setDictLabel(rentalIdName);
                SysDictData data = sysDictDataMapper.selectDictData(sysDictData);
                if (data == null) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、出租单位:" + machineryNewMon.getRentalIdName() + " 不存在");
                } else {
                    machineryNewMon.setRentalId(Integer.valueOf(data.getDictCode().toString()));    // 供应商ID

                    // 机械编号转化
                    SysDictSon sysDictSon = new SysDictSon();
                    sysDictSon.setDictCode(Integer.valueOf(data.getDictCode().toString()));
                    sysDictSon.setLable(machineryNewMon.getMachineryNumberIdName());
                    SysDictSon son = sysDictDataMapper.selectDictSonByCodeAndLable(sysDictSon);

                    if (son != null) {
                        machineryNewMon.setMachineryNumberId(son.getId());      // 物料名称ID
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、机械编号:" + machineryNewMon.getMachineryNumberIdName() + " 不存在");
                    }
                }
                machineryNewMon.setCompanyId(machineryNewMonth.getCompanyId());
                machineryNewMon.setProgramId(machineryNewMonth.getProgramId());

                // Step2 唯一性校验：同一个项目下,月份、出租单位、机械编号的唯一性
                Machinery machinery = new Machinery();
                CopyUtils.Copy(machineryNewMon, machinery);
                int count = manageMapper.checkMachineryUniqueAddMonth(machinery);
                if (count > 0) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、项目下,月份、出租单位、机械编号不符合唯一性");
                }else{
                    manageMapper.insertMachineryMonth(machinery);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、出租单位:" + machinery.getRentalIdName() + " 导入成功");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、出租单位 " + machineryNewMon.getRentalIdName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    @Transactional
    public String importMaters(List<MaterImport> list, MaterImport materImport) {
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new BusinessException("导入材料月数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (MaterImport mater : list) {
            try {
                // Step1 转化名称转ID
                String dateString = mater.getActualMonth().trim();
                String dateStr = FormatDate(dateString).substring(0, 7);
                mater.setActualMonth(dateStr);

                // 供应商转化
                String supplierIdName = mater.getSupplierIdName();
                SysDictData sysDictData = new SysDictData();
                sysDictData.setDictLabel(supplierIdName);
                SysDictData data = sysDictDataMapper.selectDictData(sysDictData);
                if (data == null) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、供应商名称:" + mater.getSupplierIdName() + " 不存在");
                } else {
                    mater.setSupplierId(Integer.valueOf(data.getDictCode().toString()));    // 供应商ID

                    // 物料名称转化
                    SysDictSon sysDictSon = new SysDictSon();
                    sysDictSon.setDictCode(Integer.valueOf(data.getDictCode().toString()));
                    sysDictSon.setLable(mater.getMaterName());
                    SysDictSon son = sysDictDataMapper.selectDictSonByCodeAndLable(sysDictSon);

                    if (son != null) {
                        mater.setMaterId(son.getId());      // 物料名称ID
                        SysDictData dictData = new SysDictData();
                        // 单位名称转化
                        dictData.setDictLabel(mater.getUnitName());
                        SysDictData reData = sysDictDataMapper.selectDictData(dictData);
                        if (reData != null) {
                            mater.setUnitNameId(Integer.valueOf(reData.getDictCode().toString()));    // 单位名称
                        } else {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、单位名称:" + mater.getUnitName() + " 不存在");
                        }
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、物料名称:" + mater.getSupplierIdName() + " 不存在");
                    }
                }
                mater.setCompanyId(materImport.getCompanyId());
                mater.setProgramId(materImport.getProgramId());

                // Step2 唯一性校验：校验同一个项目下,供应商、物料名称、规格型号的唯一性
                Mater materObj = new Mater();
                CopyUtils.Copy(mater, materObj);
                int count = manageMapper.checkMaterUniqueAdd(materObj);
                if (count > 0) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、项目下,供应商、物料名称、规格型号、月份不符合唯一性");
                }else{
                    manageMapper.addMater(materObj);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、供应商名称:" + mater.getSupplierIdName() + " 导入成功");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、供应商名称 " + mater.getSupplierIdName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
